import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/components/back_btn_icon.dart';
import 'package:share_fit/app/controllers/space/person/choise_dialog.dart';
import 'package:share_fit/app/controllers/space/person/del_dialog_view.dart';
import 'package:share_fit/app/controllers/space/person/logout_dialog_view.dart';
import 'package:share_fit/app/controllers/space/person/name_dialog.dart';
import 'package:share_fit/app/controllers/space/person/person_logic.dart';
import 'package:share_fit/app/controllers/space/space_const.dart';
import 'package:share_fit/app/controllers/space/space_logic.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/tools/app_util.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/app/tools/unit_util.dart';
import 'package:share_fit/generated/locales.g.dart';

import 'person_const.dart';

class PersonPage extends StatelessWidget {
  static const nameViewId = 'person_name';
  static const genderViewId = 'person_gender';
  static const ageViewId = 'person_age';
  static const heightViewId = 'person_height';
  static const weightViewId = 'person_weight';

  final spaceLogic = Get.put(SpaceLogic());
  final logic = Get.put(PersonLogic());
  double frontSize = 42.sp;
  double rightPadding = 50.w;

  PersonPage({super.key});

  @override
  Widget build(BuildContext context) {
    logic.loadPersonalData();

    return Scaffold(
      resizeToAvoidBottomInset: false,
      // backgroundColor: Color(0xFFF5F9FB),
      appBar: AppBar(
        // backgroundColor: Color(0xFFF5F9FB),
        title: Text(
          LocaleKeys.person_info.ts,
          style: TextStyle(fontSize: 54.sp, color: ColorConst.btnFontColor),
        ),
        centerTitle: true,
        leading: BackBtnIcon(onTap: () => Get.back()),
      ),
      body: SingleChildScrollView(
        child: Container(
          margin: EdgeInsets.all(42.w),
          child: Column(
            children: [
              Ink(
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
                  ),
                  child: InkResponse(
                    onTap: () => Get.toNamed('/space/person/avatar'),
                    splashColor: ColorConst.activeColor,
                    borderRadius: const BorderRadius.vertical(top: Radius.circular(10)),
                    highlightShape: BoxShape.rectangle,
                    highlightColor: ColorConst.activeColor,
                    containedInkWell: true,
                    child: Container(
                      padding: EdgeInsets.fromLTRB(60.w, 70.h, 42.w, 70.h),
                      child: Row(
                        children: [
                          Text(
                            LocaleKeys.person_avatar.ts,
                            style: TextStyle(fontSize: frontSize),
                          ),
                          Expanded(child: Container()),
                          GetBuilder<PersonLogic>(
                              id: "person_avatar",
                              builder: (_) {
                                return Padding(
                                    padding: EdgeInsets.only(right: rightPadding),
                                    child: Visibility(
                                        visible: logic.state.avatar.isNotEmpty,
                                        replacement: Container(
                                          margin: EdgeInsets.only(top: 42.h),
                                          alignment: Alignment.center,
                                          width: 161.w,
                                          height: 161.h,
                                          child: Image.asset('assets/images/space/icon_avatar_default.png'),
                                        ),
                                        child: Container(
                                            width: 161.w,
                                            height: 161.h,
                                            decoration: BoxDecoration(
                                                borderRadius: BorderRadius.circular(50),
                                                image: DecorationImage(fit: BoxFit.fill, image: FileImage(File(logic.state.avatar)))))));
                              }),
                          Image.asset(
                            "assets/images/space/icon_space_arrow.png",
                            width: 24.w,
                            height: 54.w,
                          )
                        ],
                      ),
                    ),
                  )),
              const Divider(height: 0),
              _buildItem(LocaleKeys.person_name.ts, nameViewId, false, false, onTap: () {
                showDialog(
                    context: context,
                    builder: (_) {
                      return TextFieldDialog(
                        title: LocaleKeys.person_set_name.ts,
                        callback: (res) {
                          // storage.write("space_person_name", res);
                          // logic.setNickName(res);
                          spaceLogic.setNickName(logic.state.nickName);
                        },
                      );
                    });
              }),
              const Divider(height: 0),
              _buildItem(
                LocaleKeys.person_gender.ts,
                genderViewId,
                false,
                false,
                onTap: () => showDialog(
                  context: context,
                  builder: (_) {
                    var initItem = '';
                    if (logic.state.genderIndex >= 0) {
                      initItem = genders[logic.state.genderIndex];
                    }

                    return ChoiceDialog(
                      title: LocaleKeys.person_choice_gender.ts,
                      initialItem: initItem,
                      unit: "",
                      pickerLists: genders,
                      callback: (index, value) => logic.setGender(index),
                    );
                  },
                ),
              ),
              const Divider(height: 0),
              _buildItem(LocaleKeys.person_age.ts, ageViewId, false, false, onTap: () {
                showDialog(
                    context: context,
                    builder: (_) {
                      return ChoiceDialog(
                        title: LocaleKeys.person_choice_age.ts,
                        initialItem: '${logic.state.ageIndex + 1}',
                        unit: "",
                        pickerLists: SpaceConst.ages.reversed.toList(),
                        callback: (index, value) {
                          logic.save(PersonConst.spacePersonAge, index, global: true);
                          logic.setAge(index);
                        },
                      );
                    });
              }),
              const Divider(height: 0),
              _buildItem(LocaleKeys.setting_unit.ts, '', false, false, onTap: () async {
                await Get.toNamed('/space/setting/unit');
                logic.update([heightViewId, weightViewId]);
              }),
              const Divider(height: 0),
              _buildItem(LocaleKeys.person_height.ts, heightViewId, false, false, onTap: () {
                showDialog(
                    context: context,
                    builder: (_) {
                      return ChoiceDialog(
                        title: LocaleKeys.person_choice_height.ts,
                        initialItem: logic.getPersonalHeight().toString(),
                        unit: UnitUtil.getLengthUnitName(),
                        pickerLists: UnitUtil.getHeightList(),
                        callback: (index, value) {
                          logic.setHeight(value);
                        },
                      );
                    });
              }),
              const Divider(height: 0),
              _buildItem(LocaleKeys.person_weight.ts, weightViewId, false, true, onTap: () {
                showDialog(
                    context: context,
                    builder: (_) {
                      return ChoiceDialog(
                        title: LocaleKeys.person_choice_weight.ts,
                        initialItem: logic.getPersonalWeight().toString(),
                        unit: UnitUtil.getWeightUnitName(),
                        pickerLists: UnitUtil.getWeightList(),
                        callback: (index, value) {
                          logic.setWeight(value);
                        },
                      );
                    });
              }),
              SizedBox(
                height: 120.h,
              ),
              GetBuilder<PersonLogic>(
                  id: 'person_bottom_widget',
                  builder: (_) {
                    return Visibility(
                        visible: logic.read('login_state', defaultValue: false, global: true),
                        replacement: Container(
                          height: 136.h,
                          width: 1.sw,
                          margin: EdgeInsets.fromLTRB(42.w, 0, 42.w, 120.h),
                          child: ElevatedButton(
                            onPressed: () async {
                              var result = await Get.toNamed('/login', arguments: {'toMainPage': true});
                              if (result != null && result.containsKey('space_person_name')) {
                                logic.state.nickName = result['space_person_name'];
                              }
                              logic.update([nameViewId, 'person_bottom_widget']);
                              spaceLogic.update(['space_name', 'space_user_id']);
                            },
                            style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(ColorConst.activeColor),
                                shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)))),
                            child: Text(
                              LocaleKeys.space_account_login.ts,
                              style: TextStyle(
                                fontSize: 48.sp,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                        child: Column(
                          children: [
                            Container(
                              height: 136.h,
                              width: 1.sw,
                              margin: EdgeInsets.fromLTRB(42.w, 0, 42.w, 0.h),
                              child: ElevatedButton(
                                onPressed: () {
                                  showDialog(
                                      context: context,
                                      builder: (_) {
                                        return LogoutDialog(callback: () {
                                          AppUtil.clearLoginInfo();
                                          // Get.offAllNamed('/main');
                                          Get.until((route) => Get.currentRoute == '/main');
                                        });
                                      });
                                },
                                style: ButtonStyle(
                                    backgroundColor: MaterialStateProperty.all(ColorConst.activeColor),
                                    shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)))),
                                child: Text(
                                  LocaleKeys.space_account_logout.ts,
                                  style: TextStyle(
                                    fontSize: 48.sp,
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ),
                            Container(
                              height: 136.h,
                              width: 1.sw,
                              margin: EdgeInsets.fromLTRB(42.w, 50.h, 42.w, 120.h),
                              child: ElevatedButton(
                                onPressed: () {
                                  showDialog(
                                      context: context,
                                      builder: (_) {
                                        return DelDialog(callback: () {
                                          Navigator.pop(context);
                                          Get.toNamed('/space/account/del');
                                        });
                                      });
                                },
                                style: ButtonStyle(
                                    backgroundColor: MaterialStateProperty.all(ColorConst.secondaryFontColor),
                                    shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)))),
                                child: Text(
                                  LocaleKeys.space_account_del.ts,
                                  style: TextStyle(
                                    fontSize: 48.sp,
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ));
                  }),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildItem(title, id, isFirst, isLast, {onTap}) {
    var borderRadius = BorderRadius.circular(0);
    if (isFirst && !isLast) {
      borderRadius = const BorderRadius.vertical(top: Radius.circular(10));
    } else if (!isFirst && isLast) {
      borderRadius = const BorderRadius.vertical(bottom: Radius.circular(10));
    } else if (isFirst && isLast) {
      borderRadius = BorderRadius.circular(10);
    }
    Widget widget = Ink(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: borderRadius,
        ),
        child: InkResponse(
          onTap: onTap,
          splashColor: ColorConst.activeColor,
          borderRadius: borderRadius,
          highlightShape: BoxShape.rectangle,
          highlightColor: ColorConst.activeColor,
          containedInkWell: true,
          child: Container(
            padding: EdgeInsets.fromLTRB(60.w, 60.h, 36.w, 60.h),
            child: Row(
              children: [
                Text(
                  title,
                  style: TextStyle(fontSize: frontSize),
                ),
                Expanded(child: Container()),
                GetBuilder<PersonLogic>(
                    id: id,
                    builder: (_) {
                      return Padding(
                          padding: EdgeInsets.only(right: rightPadding),
                          child: Text(
                            getState(id),
                            style: TextStyle(fontSize: frontSize),
                          ));
                    }),
                Image.asset(
                  "assets/images/space/icon_space_arrow.png",
                  width: 24.w,
                  height: 54.h,
                )
              ],
            ),
          ),
        ));
    return widget;
  }

  final List genders = [LocaleKeys.person_gender_secrecy.ts, LocaleKeys.person_gender_male.ts, LocaleKeys.person_gender_female.ts];

  String getState(String id) {
    String result = '';
    switch (id) {
      case nameViewId:
        result = logic.state.nickName;
        break;
      case genderViewId:
        if (logic.state.genderIndex == -1) {
          return '';
        }
        result = genders[logic.state.genderIndex];
        break;
      case ageViewId:
        if (logic.state.ageIndex == -1) {
          return '';
        }
        result = SpaceConst.ages.reversed.toList()[logic.state.ageIndex];
        break;
      case heightViewId:
        if (logic.state.personalHeight <= 0) {
          return '';
        }
        result = "${logic.getPersonalHeight()} ${UnitUtil.getLengthUnitName()}";
        break;
      case weightViewId:
        if (logic.state.personalWeight <=0 ) {
          return '';
        }
        result = "${logic.getPersonalWeight()} ${UnitUtil.getWeightUnitName()}";
        break;
    }
    return result;
  }
}
